import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件
import login from '@/views/login'
import store from '@/store'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  {path: '/', redirect: '/layout/home'},
  { path: '/login', component: login },
  {
    path: '/layout', 
    component: () => import('@/views/layout/index.vue'), 
    children: [
      { path: 'home', component: () => import('@/views/layout/home'), meta: {needKeep: true} },
      { path: 'ask', component: () => import('@/views/layout/ask')},
      { path: 'video', component: () => import('@/views/layout/video')},
      { path: 'my', component: () => import('@/views/layout/my'), meta: {needLogin: true} },
    ]
  },
  { path: '/my/edit', component: () => import('@/views/layout/my/edit.vue'), meta: {needLogin: true} },
  { path: '/home/detail', component: () => import('@/views/detail')},
  { path: '/home/search', component: () => import('@/views/search')},
  { path: '/search/result', component: () => import('@/views/result')},
  { path: '/my/zhi', component: () => import('@/views/zhi'), meta: {needLogin: true}},
]

const router = new VueRouter({
  routes
})

// 获取一次即可，真的吗？
// const token = store.state.token.token
// 导航守卫
router.beforeEach((to, from, next) => {
  // to：要跳转到的路由对象
  // from：从哪个路由中跳转过来
  // next：函数，是否继续向下执行
  const needLogin = to.meta.needLogin
  if (needLogin) {
    const token = store.state.token.token
    if (token) {
      next()
    } else {
      Toast.fail("您还没有登录")
      next(`/login?url=${to.path}`)
    }
  } else {
    next()
  }
})

export default router
